package com.sl.water.api.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sl.common.ResponseData;
import com.sl.common.exception.GlobalErrorCodeEnum;
import com.sl.water.api.RehearsalPythonService;
import com.sl.water.entity.RehearsalScheme;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class RehearsalPythonServiceImpl implements RehearsalPythonService {

    @Value("${python-model.script:}")
    private String scriptPath;

    @Value("${python-server.base-url:}")
    private String baseUrl;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public ResponseData executePythonScript(String scriptName, List<String> arguments) {
        // 构建命令
        List<String> command = new ArrayList<>();
        // 根据环境可能需要调整为python
        command.add("python");
        command.add(scriptPath + scriptName);
        command.addAll(arguments);
        StringBuilder output = new StringBuilder();
        try {
            // 创建进程并执行命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            // 获取Python脚本的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info(line);
                output.append(line).append("\n");
            }
            // 等待进程执行完成并获取返回值
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                log.error("Python脚本执行失败，返回码: " + exitCode);
                return ResponseData.error(GlobalErrorCodeEnum.MODEL_CALCULATION_FAILED, output.toString());

            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return ResponseData.error(GlobalErrorCodeEnum.MODEL_CALCULATION_FAILED, e.getMessage());
        }
        return ResponseData.success(output.toString());
    }

    @Override
    public ResponseData callPythonApi(RehearsalScheme rehearsalScheme, String kind) {
        try{
            String param = rehearsalScheme.getParamsFh();
            if ("bfh".equals(kind)) {
                param = rehearsalScheme.getParamsBfh();
            }
            Map<String, Object> params = new HashMap<>();
            params.put("kind", kind);
            params.put("sId", rehearsalScheme.getId());
            params.put("createdTime", rehearsalScheme.getCreatedTime().toLocalDate().toString().replace("-", "/"));
            params.put("param", JSONUtil.parseArray(param));
            params.put("simulationDuration", rehearsalScheme.getSimulationDuration());
            String ret = restTemplate.postForObject(baseUrl + "/run", params, String.class);
            return ResponseData.success(ret);
        }catch (Exception e) {
            throw new RuntimeException("调用Python模型预测服务异常:"+e.getMessage());
        }

    }

    @Override
    public ResponseEntity<byte[]> callImageApi(String filePath) {
        Map<String, String> params = new HashMap<>();
        params.put("filePath", filePath);
        try {
            byte[] imageByte = restTemplate.getForObject(baseUrl + "/image?file_path={filePath}", byte[].class, params);
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.IMAGE_PNG);
            return new ResponseEntity<>(imageByte, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseData<List<BigDecimal>> calRainfallList(Integer duration, BigDecimal rainfall) {
        try{

            Map<String, Object> params = new HashMap<>();
            //duration分钟
            params.put("duration", duration * 60);
            params.put("rainfall", rainfall);
            List result = restTemplate.getForObject(baseUrl + "/calRainfallList?duration={duration}&rainfall={rainfall}", List.class, params);
            List<BigDecimal> bigDecimalList = new ArrayList<>();
            if (result != null) {
                result.forEach(value -> bigDecimalList.add(new BigDecimal(String.valueOf(value))));
            }
            return ResponseData.success(bigDecimalList);
        }catch (Exception e) {
            throw new RuntimeException("调用Python降雨计算服务异常:"+e.getMessage());
        }
    }

    @Override
    public ResponseData<JSONObject> calImageListApi(LocalDateTime createdTime, long id, String kind) {
        Map<String, Object> params = new HashMap<>();
        params.put("create_time", createdTime);
        params.put("s_id", id);
        params.put("kind", kind);
        JSONObject result = restTemplate.getForObject(baseUrl + "/imageObj?kind={kind}&create_time={create_time}&s_id={s_id}", JSONObject.class, params);
        return ResponseData.success(result);
    }


}
